package mk.edu.ii.navigatemacedonia;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;


public class NavigateMacedonia extends Activity implements LocationListener, OnClickListener {
	
	private static final String USER_PREFERENCE = "user_preference";
	private static int REQUEST_CODE = 1000;
	
	ArrayList<Site> sites=new ArrayList<Site>();
	Handler handler = new Handler(); 
	
	LocationManager myLocationManager;
	View view;
	Spinner radiusSpiner;
    Spinner categorySpiner;
    ProgressDialog myProgressDialog = null;
    String provider = null;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.nm_mainview);
        
        // check if user is logged in,
        // if not then it is switched to login view
        checkLogKey();
       // NMContentProvider provider = new NMContentProvider();
        
        radiusSpiner = (Spinner)findViewById(R.id.first_RadiusSpiner);
        categorySpiner = (Spinner)findViewById(R.id.first_CategorySpiner);
        
        CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
        checkBox.setChecked(false);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					pickLocation();
				}
			}
		});
      
        populateSpinners(radiusSpiner,R.array.radius);
        populateSpinners(categorySpiner,R.array.category);
        
        
        final Button searchButton = (Button) findViewById(R.id.SearchButton);
         
		searchButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				
				searchButton();
			}
			
		});
		
		// get reference to Location Manager and Location Provider
		myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		((ImageButton)findViewById(R.id.distance_left_button)).setOnClickListener(this);
		((ImageButton)findViewById(R.id.distance_right_button)).setOnClickListener(this);
		((ImageButton)findViewById(R.id.category_left_button)).setOnClickListener(this);
		((ImageButton)findViewById(R.id.category_right_button)).setOnClickListener(this);
		((ImageButton)findViewById(R.id.logout_button)).setOnClickListener(this);
	}
    
	public Location getMyLocation() {

		try {
			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			
			Location location = myLocationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			

			if (location == null) {
				criteria.setAccuracy(Criteria.ACCURACY_COARSE);
				provider = myLocationManager.getBestProvider(criteria, false);
				location = myLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			}
			if (location == null){
				List<String> providers = myLocationManager.getAllProviders();
				int bestAccuracy = 10;
				for(int i=0;i<providers.size();i++){
					LocationProvider locationProvider = myLocationManager.getProvider(providers.get(i)); 
					if(locationProvider.getAccuracy() < bestAccuracy){
						bestAccuracy = locationProvider.getAccuracy();
						location = myLocationManager.getLastKnownLocation(providers.get(i));
					}
				}
			}
			return location;
		} catch (Exception e) {
			Toast toast = Toast.makeText(getApplicationContext(),
					"Your location can not be determined!", Toast.LENGTH_SHORT);
			toast.show();

		}
		return null;
    }
    
    public void populateSpinners(Spinner spinner,int id){
    	
    	
    	ArrayAdapter<CharSequence> aAdapter;
    	
    	//Adapter a = new ArrayAdapter(getApplicationContext(),R.layout.spinner_item,list)
    	aAdapter = ArrayAdapter.createFromResource(this,id,R.layout.spinner_item);
    	
    	aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spinner.removeAllViewsInLayout();
    	spinner.setAdapter(aAdapter);
    	//spinner.setSelection(1);
    }
    
    
    protected void onResume() {
    	Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		provider = myLocationManager.getBestProvider(criteria, true);
    	myLocationManager.requestLocationUpdates(provider, 20000, 1f, this);
    	restoreUIState();
    	super.onResume();    	  	
    }
    
    @Override
    protected void onPause(){
    	
    	myLocationManager.removeUpdates(this);
    	saveUIState();
    	super.onPause();
    	
    }
    
    public void pickLocation(){
    	
    	Intent pickLocationIntent = new Intent(getApplicationContext(),PickLocationMapView.class);
    	startActivityForResult(pickLocationIntent,REQUEST_CODE);
    }
    
    public void searchButton(){
    	
    	CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
		Location location = new Location(LocationManager.GPS_PROVIDER);
		
		int[] rad= {100,250,500,1000,1500,2000,5000};
		
		Intent intent = getIntent();
		if(checkBox.isChecked() && intent!=null){
			location.setLatitude(intent.getDoubleExtra("latitude", 0d));
			location.setLongitude(intent.getDoubleExtra("longitude", 0d));	
		}else{
			location=getMyLocation();
		}
		if(location!=null){
			
			Intent resultsView = new Intent(getApplicationContext(),ResultsView.class);
		
			resultsView.putExtra("longitude", location.getLongitude());
			resultsView.putExtra("latitude", location.getLatitude());
			resultsView.putExtra("radius", rad[radiusSpiner.getSelectedItemPosition()]);
			resultsView.putExtra("category", categorySpiner.getSelectedItemPosition());
			resultsView.putExtra("searchText", ((EditText)findViewById(R.id.EditText01)).getText().toString());
	    	startActivity(resultsView);
	    
		}else{
			Toast.makeText(getApplicationContext(), getString(R.string.no_location), 3000).show();
		}
    }
    private void saveUIState(){
    	//     	Get the activity preferences object.
    	SharedPreferences uiState = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    	 
    	// Get the preferences editor.
    	SharedPreferences.Editor editor = uiState.edit();
    	// Add the UI state preference values.
    	CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
    	radiusSpiner = (Spinner)findViewById(R.id.first_RadiusSpiner);
        categorySpiner = (Spinner)findViewById(R.id.first_CategorySpiner);
        
    	editor.putBoolean("CHECK_BOX", checkBox.isChecked());
    	editor.putLong("radius", radiusSpiner.getSelectedItemPosition());
    	editor.putLong("category", categorySpiner.getSelectedItemPosition());
    	// Commit the preferences.
    	editor.commit();
    }
    
    private void restoreUIState() {
    	// Get the activity preferences object.
    	SharedPreferences settings = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    	// Read the UI state values, specifying default values.
    	
    	//Boolean check_box = settings.getBoolean("CHECK_BOX", false);
    	// Restore the UI to the previous state.
    	//CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
    	radiusSpiner = (Spinner)findViewById(R.id.first_RadiusSpiner);
        categorySpiner = (Spinner)findViewById(R.id.first_CategorySpiner);
        
    	//checkBox.setChecked(check_box);
    	radiusSpiner.setSelection((int)settings.getLong("radius", 0));
    	categorySpiner.setSelection((int)settings.getLong("category", 0));
    	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	
    	//menu.add(1,1,Menu.NONE,"Logout");
    	//menu.add(1,2,Menu.NONE,"Update");
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	super.onOptionsItemSelected(item);
    	switch (item.getItemId()) {
       	case 1:{
       		logout();
       		return true;
       	}
       	case 2:{
       		
       		return true;
       	}
       	
    	}
    	return true;
    }
    
    private void logout(){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage(getString(R.string.logout_q))
    	       .setCancelable(false)
    	       .setPositiveButton(getString(R.string.logout_yes), new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   SharedPreferences pref = getSharedPreferences(LoginView.LOG_KEY_PREFERENCE, Activity.MODE_PRIVATE);
    	           	Editor editor = pref.edit();
    	           	editor.putString("key", null);
    	           	editor.commit();
    	           	Intent logoutIntent = new Intent(getApplicationContext(),LoginView.class);
    	           	startActivity(logoutIntent);
    	           	finish();
    	           }
    	       })
    	       .setNegativeButton(getString(R.string.logout_no), new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.show();
    }
    
    private void checkLogKey(){
    	SharedPreferences pref = getSharedPreferences(LoginView.LOG_KEY_PREFERENCE, Activity.MODE_PRIVATE);
		if(pref.getString("key", null)== null){
        	
        	Intent logoutIntent = new Intent(getApplicationContext(),LoginView.class);
    		startActivity(logoutIntent);
    		finish();
        }
    }

    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	if(resultCode==RESULT_OK && requestCode==REQUEST_CODE){
			setIntent(data);
		}
	}
    
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.distance_left_button:
			int currentPosition = radiusSpiner.getSelectedItemPosition();
			if ((currentPosition - 1) >= 0) {
				radiusSpiner.setSelection(currentPosition - 1, true);
			}
			break;
		case R.id.distance_right_button:
			int size = radiusSpiner.getAdapter().getCount();
			currentPosition = radiusSpiner.getSelectedItemPosition();
			if ((currentPosition + 1) < size) {
				radiusSpiner.setSelection(currentPosition + 1, true);
			}
			break;
		case R.id.category_left_button:
			currentPosition = categorySpiner.getSelectedItemPosition();
			if ((currentPosition - 1) >= 0) {
				categorySpiner.setSelection(currentPosition - 1, true);
			}
			break;
		case R.id.category_right_button:
			size = categorySpiner.getAdapter().getCount();
			currentPosition = categorySpiner.getSelectedItemPosition();
			if ((currentPosition + 1) < size) {
				categorySpiner.setSelection(currentPosition + 1, true);
			}
			break;
		case R.id.logout_button:
			logout();
			break;
		default:
			break;
		}
	}
    
}